package com.reder.practice.controller;

import com.reder.practice.bean.LoginInfo;
import com.reder.practice.common.dto.ServerResponse;
import com.reder.practice.common.util.PageUtil;
import com.reder.practice.common.util.SessionUtil;
import com.reder.practice.service.ManagerService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 管理员 API 层
 *
 * @author Fish
 * <p>Email: fishinlove@163.com</p>
 * <p>created by 2019/09/24 12:09:04</p>
 */
@ApiOperation("管理员 API")
@RestController
@RequestMapping(path = "/manager")
public class ManagerController {

    @Resource
    private ManagerService managerService = null;

    @ApiOperation("登录")
    @RequestMapping(method = RequestMethod.POST, path = "/login")
    @SuppressWarnings("unchecked")
    public ServerResponse login(@ApiParam("用户名") String username,
                                @ApiParam("密码") String password,
                                @ApiIgnore HttpSession session) {
        ServerResponse<LoginInfo> response = managerService.login(username, password);
        if (response.isSuccess()) {
            SessionUtil.putLoginInfoToSession(response.getData(), session);
        }
        return response;
    }

    @ApiOperation("判断用户名是否已经存在，用于注册新增管理员")
    @RequestMapping(method = RequestMethod.GET, path = "/exists")
    public ServerResponse isUsernameExisted(@ApiParam("要判断的用户名") String username) {
        return managerService.isUsernameExisted(username);
    }

    @ApiOperation("添加管理员")
    @RequestMapping(method = RequestMethod.POST, path = "/add")
    public ServerResponse addManager(@ApiParam("用户名，需要检查是否已经存在") String username,
                                     @ApiParam("真实姓名") String realName,
                                     @ApiParam("密码") String password) {
        return managerService.addManager(username, realName, password);
    }

    @ApiOperation("分页列出所有管理员")
    @RequestMapping(method = RequestMethod.GET, path = "/list")
    public ServerResponse listUsers(@ApiParam("第几页数据，默认为 1") @RequestParam(defaultValue = 1 + "") int pageNumber,
                                    @ApiParam("一页显示多少条数据，默认为 12") @RequestParam(defaultValue = PageUtil.DEFAULT_SIZE_OF_ONE_PAGE + "") int sizeOfOnePage) {
        return managerService.listManagers(pageNumber, sizeOfOnePage);
    }

    @ApiOperation("删除管理员")
    @RequestMapping(method = RequestMethod.DELETE, path = "/remove")
    public ServerResponse removeUser(@ApiParam("要被删除的管理员的 id") long id) {
        return managerService.removeManager(id);
    }
}
